package org.tso.bs.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import org.apache.log4j.Logger;

/**
 * 协议头 <br/>
 * 协议内容（协议标示 名称 版本 字符集 处理标示 内容长度）： <br/>
 * BSTALK DP 0 GBK REG 7(\n) <br/>
 * CONTENT<br/>
 * <br/>
 * 处理标示:<br/>
 * REG 注册，LGN 登录
 * 
 * @author LiuChuanfeng
 * 
 */
public class Head {
	Logger log=Logger.getLogger(Head.class);
	public static final String PROTOCOL_NAME = "BSTALK DP";
	private Socket socket;
	private String name;
	private String version;
	private String handlerName;
	private String encoding;
	private int length;

	public Head(Socket socket) throws ProtocolException, IOException {
		this.socket = socket;
		analyse();
	}

	private void analyse() throws ProtocolException, IOException {
		InputStream is = this.socket.getInputStream();
		int data;
		// 判断标示
		byte sign[] = new byte[9];
		log.debug("等待用户输入头。");
		is.read(sign);
		String signStr = new String(sign);
		if (!PROTOCOL_NAME.equals(signStr)) {
			throw new ProtocolException("错误的协议输入，协议标示因为:" + PROTOCOL_NAME
					+ "，但输入:" + signStr);
		}
		this.setName(signStr);
		// 协议头内容
		StringBuffer sb = new StringBuffer();
		while (true) {
			data = is.read();
			if (data == -1 || data == '\n')
				break;
			sb.append((char) data);
		}
		String[] content = sb.toString().split(" ");
		this.setVersion(content[1]);
		this.setEncoding(content[2]);
		this.setHandlerName(content[3]);
		this.setLength(new Integer(content[4]));
	}

	public Socket getSocket() {
		return socket;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getHandlerName() {
		return handlerName;
	}

	public void setHandlerName(String handlerName) {
		this.handlerName = handlerName;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

}
